﻿using AutoMapper;
using MediatR;
using MySqlX.XDevAPI.Common;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.RBAC;

namespace RBAC_Set.API.Application.Commands
{
    public class AddUsersHandler : IRequestHandler<AddUsersCommand, THE_WIND_RISES.Common.Dtos.Result>
    {
        public IBaseRepository<User> UserRep { get; set; }
        public IBaseRepository<UserRole> UserRoleRep { get; set; }
        public IMapper mapper { get; set; }
        public ILogger<AddUsersHandler> logger;

        public AddUsersHandler(IBaseRepository<User> userRep, IMapper mapper, IBaseRepository<UserRole> userRoleRep, ILogger<AddUsersHandler> logger)
        {
            UserRep = userRep;
            this.mapper = mapper;
            UserRoleRep = userRoleRep;
            this.logger = logger;
        }

        /// <summary>
        /// 添加用户信息  及其  用户角色关联信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<THE_WIND_RISES.Common.Dtos.Result> Handle(AddUsersCommand request, CancellationToken cancellationToken)
        {
            var result = new THE_WIND_RISES.Common.Dtos.Result() { Code = (int)CommonErrorCodes.Added };
            try
            {
                var AddNum = 0;
                string UserShowSql = $"select * from User where UserName = '{request.UserName}' ";

                var Userres = UserRep.GetAll(UserShowSql).FirstOrDefault();
                if (Userres == null)
                {
                    logger.LogInformation($"{request.UserName}用户信息为空，进行添加");
                    var AddData = mapper.Map<User>(request);
                    string sql = "insert into User values(@UserId,@UserName,@UserPwd,@UserState,@IsDelete,@Handle,@HandleContext,@HandleTime,@Pid);";
                    AddNum = UserRep.Add(sql, AddData);
                    string UserShowSql1 = $"select * from User where UserName = '{request.UserName}' ";

                    Userres = UserRep.GetAll(UserShowSql1).FirstOrDefault();
                }
                string ShowUserRoleSql = $"select * from UserRole where UserId = {Userres.UserId} and RoleId = {request.RoleId}";
                var ShowUserRoleres = UserRoleRep.GetAll(ShowUserRoleSql).FirstOrDefault();
                if (ShowUserRoleres == null)
                {
                    logger.LogError($"用户角色信息为空，进行添加用户角色关联信息");
                    string UserRoleAddSql = "insert into UserRole values(@UserRoleId,@UserId,@RoleId,@IsDelete);";
                    var AddUserRoleres = UserRoleRep.Add(UserRoleAddSql, new
                    {
                        UserRoleId = 0,
                        UserId = Userres.UserId,
                        RoleId = request.RoleId,
                        IsDelete = false
                    });
                    string ShowUserRoleSql1 = $"select * from UserRole where UserId = {Userres.UserId} and RoleId = {request.RoleId}";
                    ShowUserRoleres = UserRoleRep.GetAll(ShowUserRoleSql1).FirstOrDefault();
                }
                if (Userres != null && ShowUserRoleres != null)
                {
                    AddNum += 1;
                }
                else
                {
                    logger.LogError($"添加用户信息失败，用户或用户角色信息重复");
                    result.Code = (int)CommonErrorCodes.Added;
                    result.Data = null;
                    result.Msg = "添加失败，角色名称和权限信息重复";
                    return result;
                }
                if (AddNum > 0)
                {
                    result.Code = (int)CommonErrorCodes.Success;
                    result.Data = null;
                    result.Msg = "添加成功";
                    logger.LogInformation($"添加成功");
                    return result;
                }

            }
            catch (Exception)
            {
                logger.LogError($"添加用户信息失败，用户或用户角色信息重复");
                throw;
            }
            result.Code = (int)CommonErrorCodes.Added;
            result.Data = null;
            result.Msg = "添加失败，角色名称和权限信息重复";
            return result;
        }
    }
}
